import { defineStore } from "pinia";

export const useTodosStore = defineStore("todos", {
  state() {
    return {
      list: JSON.parse(localStorage.getItem("todos")) || [
        {
          id: 1,
          name: "吃饭",
          done: false,
        },
        {
          id: 2,
          name: "睡觉",
          done: true,
        },
        {
          id: 3,
          name: "打豆豆",
          done: false,
        },
      ],
      filters: ["All", "Active", "Completed"],
      active: "All",
    };
  },

  getters: {
    isCheckAll() {
      return this.list.length > 0 && this.list.every((v) => v.done);
    },
    // 计算未完成项
    leftCount() {
      return this.list.filter((v) => !v.done).length;
    },

    // 根据状态，计算列表
    filterList() {
      console.log("this.active -----> ", this.active);
      if (this.active === "All") {
        return this.list;
      } else if (this.active === "Active") {
        return this.list.filter((v) => !v.done);
      } else if (this.active === "Completed") {
        return this.list.filter((v) => v.done);
      }
    },
  },

  actions: {
    // 修改状态
    change(id) {
      //   console.log("id", id);
      const obj = this.list.find((v) => v.id === id);
      obj.done = !obj.done;
    },
    // 删除数据
    del(id) {
      // console.log("id", id);
      this.list = this.list.filter((v) => v.id !== id);
    },

    // 添加数据
    add(name) {
      // console.log("name", name);
      this.list.unshift({
        id: +new Date(),
        name,
        done: false,
      });
    },

    // 全选/反选
    toggleAll(bl) {
      console.log("bl", bl);
      this.list.forEach((v) => (v.done = bl));
    },

    // 清理已完成
    clearDone() {
      this.list = this.list.filter((v) => !v.done);
    },

    // 改变当前状态
    changeActive(item) {
      this.active = item;
    },
  },
});
